<template>
	<view class="container">
		<view class="list">
			<view class="list_item">
				<text>電子票卷名稱</text>
				<text>{{details.title}}</text>
			</view>

			<view class="list_item">
				<text>使用範圍</text>
				<text>{{storeDetails.name}}</text>
			</view>
			<view class="list_item">
				<text>包間類型</text>
				<text>{{details.room_type_name?details.room_type_name:'所有包廂類型'}}</text>
			</view>
			<view class="list_item">
				<text>有效期至</text>
				<text>{{effectiveTime(details.end_time*1000)}}</text>
			</view>
			<view class="list_item">
				<text>使用時長(小時)</text>
				<text>{{details.used_times}}</text>
			</view>
			<view class="list_item">
				<text>預約限制</text>
				<text>{{details.is_order===1?'可用':'不可用'}}</text>
			</view>
			<view class="list_item">
				<text>續單限制</text>
				<text>{{details.is_continuation_order===1?'可用':'不可用'}}</text>
			</view>
			<view class="list_item">
				<text>優惠卷</text>
				<text class="use_coupon" @tap="show=true" v-if="list.length">{{text}}</text>
				<text class="use_coupon" v-else>暫無可用優惠券</text>
			</view>
		</view>
		<view class="service">
			<image src="/static/images/service.png" mode=""></image>
			<text>如有疑問請聯繫客服</text>
		</view>
		<view class="confirm_buy">
			<view>總計：${{price}}</view>
			<!-- <view class="confirm" @tap="showPayType=true">確定購買</view> -->
			<view class="confirm" @tap="showPayTypePopup">確定購買</view>
		</view>
		<u-popup :show="show" class="popup" mode="bottom" @close="show=false">
			<view class="popup_box">
				<scroll-view scroll-y="true" @scrolltolower="scroll">
					<view class="popup_item" :class="{active:selectCouponId==item.id}" @tap="select_coupon(item.id)"
						v-for="item in list" :key="item.id">
						<view class="list_left">
							<view class="top">
								<view class="coupon">{{item.title}}</view>
								<view class="condition">滿{{item.min}}可用</view>
							</view>
							<view class="bottom">
								<view class="number">${{item.money}}</view>
								<view class="time">有效期至{{effectiveTime(item.expire_time*1000)}}</view>
							</view>
						</view>
						<view class="list_right">
							<view>去使用</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</u-popup>

		<u-popup :show="showPayType" class="popup" mode="bottom" @close="showPayType=false">
			<view class="popup_pay" style="height: 1088rpx;width: 100%;background: #fff;">
				<view style="font-size: 30rpx;text-align: center;">支付金額</view>
				<view style="color: #FA533D;font-size: 46rpx;font-weight: bold;text-align: center;">
					${{price}}</view>
				<view style="margin: 19rpx 0 31rpx 30rpx;">選擇付款方式</view>
				<view class="payment_method">
					<radio-group @change="radioChange" class="radio_box">
						<label v-for="(item,index) in paymentMethod" :key="item.value">
							<text :class="{active:radioChecked==item.value}">{{item.value}}</text>
							<radio :value="item.value" :checked="currentCheck==index" color="#39B19D" />
						</label>
					</radio-group>
					<view class="balance" v-if="radioChecked=='餘額付款'">餘額<text
							style="margin-left: 15rpx;color: #FA533D;">{{balance}}</text></view>
					<view @tap="showCardPopup = true" class="card_text" v-if="radioChecked == '儲值卡付款'">
						<text>{{ selectCardText }}</text>
						<text style="margin-left: 30rpx;"
							v-if="rechargeCardInfo">餘額{{ rechargeCardInfo.remaining_money }}</text>
					</view>
				</view>
				<view class="confirm_payment" @tap="confirm_payment">確定支付</view>
			</view>
		</u-popup>

		<u-popup :show="showCardPopup" @close="showCardPopup = false" :closeOnClickOverlay="true" round="16"
			mode="center">
			<scroll-view scroll-y="true" class="card_popup_box">
				<view class="card_item" :class="{ active: rechargeCardInfo ? rechargeCardInfo.id == item.id : false }"
					@tap="selectCard(item)" v-for="item in rechargeCardList" :key="item.id">
					<view class="title">
						<view class="card_name">{{ item.title }}</view>
						<view class="end_time">有效期至{{ convertTime(item.expire_time * 1000) }}</view>
					</view>
					<view class="card_balance">餘額 <text>{{ item.remaining_money }}</text> </view>
				</view>
			</scroll-view>
		</u-popup>

		<u-keyboard mode="number" :show="showKeyBoard" :tips="tips.join(' ')" @change="keyboardChange"
			@backspace="keyboardBackspace" @close="cancel" @cancel="cancel"></u-keyboard>
	</view>
</template>

<script>
	import store from "@/store/index.js"
	import {
		getStoreCouponList,
		ticketRollCardBuy
	} from '@/api/index.js'
	import {
		getUserStoreInfo,
		getCouponTicketCard,
		getUserCouponAll
	} from '@/api/me.js'
	import {
		getLinePayInfo
	} from '@/api/order.js'

	export default {
		data() {
			return {
				details: "", // 電子票券詳情
				storeDetails: '', // 門店詳情
				couponList: [], // 當前門店優惠劵列表
				show: false,
				list: [], // 瞞住滿減條件的優惠劵
				selectCouponId: "", // 當前選擇的優惠劵
				text: '選擇優惠券',
				price: "",
				showPayType: false,
				paymentMethod: [{
					value: "餘額付款",
					checked: false,
				}],
				radioChecked: "",
				currentCheck: 0,
				showKeyBoard: false,
				tips: ["__", "__", "__", "__", "__", "__"],
				// 支付密碼
				payment_password: [],
				balance: '',
				selectCardText: '選擇儲值卡',
				showCardPopup: false,
				rechargeCardList: [],
				rechargeCardInfo: null,
				form: '',
				isLinePay: null,
			};
		},
		onLoad(option) {
			this.details = JSON.parse(option.details)
			console.log(this.details, '詳情')
			this.price = this.details.money
			// console.log(store.state.storeDetails,'門店詳情')
			this.storeDetails = store.state.storeDetails

			// 獲取店鋪優惠券列表
			// getStoreCouponList({
			// 	type: 1,
			// 	page: 1,
			// 	store_id: this.storeDetails.id
			// }).then(res => {
			// 	// console.log(res.data,"優惠券列表")
			// 	this.couponList = res.data
			// 	// console.log(this.couponList, "全部優惠券")
			// 	if (res.data.length) {
			// 		this.list = this.couponList.filter(item => Number(this.details.money) >= Number(item.min))
			// 		// console.log(this.list, "優惠劵")
			// 	}
			// })

			getUserCouponAll({
				store_id: this.storeDetails.id
			}).then(res => {
				// console.log(res.data,'優惠券')
				this.couponList = res.data
				// console.log(this.couponList, "全部優惠券")
				if (res.data.length) {
					this.list = this.couponList.filter(item => Number(this.details.money) >= Number(item.min))
					// console.log(this.list, "優惠劵")
				}
			})

			this.radioChecked = this.paymentMethod[0].value
		},
		onShow() {
			this.linePayFn()
		},
		methods: {
			effectiveTime(num) {
				let time = new Date(num)
				let y = time.getFullYear()
				let m = time.getMonth() + 1 >= 10 ? time.getMonth() + 1 : "0" + (time.getMonth() + 1)
				let d = time.getDate() >= 10 ? time.getDate() : "0" + (time.getDate())
				return y + "/" + m + "/" + d
			},
			scroll() {},
			select_coupon(id) {

				if (this.selectCouponId == id) {
					this.selectCouponId = ""
					this.text = "選擇優惠券"
				} else {
					this.selectCouponId = id
					this.list.forEach(item => {
						if (item.id == id) {
							this.text = item.title
						}
					})
				}
				// console.log(this.selectCouponId, "選擇")
			},
			radioChange(e) {

				this.radioChecked = e.detail.value


				this.paymentMethod.forEach((item, index) => {
					if (item.value == this.radioChecked) {
						this.currentCheck = index
						// console.log(index,"1111")
					}
				})

				// if (this.radioChecked == '餘額付款') {

				// }

				// console.log(this.currentCheck,"222")

			},
			showPayTypePopup() {
				this.showPayType = true
				getUserStoreInfo({
					store_id: this.storeDetails.id
				}).then(res => {
					// console.log(res.data,"用戶店鋪餘額信息")
					this.balance = res.data.balance
					this.rechargeCardList = res.data.recharge_card
					this.setPayment(res.data.pay_type_list)
				})
			},
			confirm_payment() {
				// this.showKeyBoard = true
				let payType = ''
				switch (this.radioChecked) {
					case '信用卡/轉帳 藍新':
						payType = 1;
						break;
					case '信用卡/轉帳 綠界':
						payType = 2;
						break;
					case 'Line Pay':
						payType = 4;
						break;
					case '餘額付款':
						payType = 6;
						break;
					case '儲值卡付款':
						payType = 7;
						break;
					case 'Apple pay':
						payType = 9
				}
				// console.log(payType,"付款方式")
				switch (payType) {
					case 1:
						this.confirm_payment1();
						break;
					case 2:
						this.confirm_payment2();
						break;
					case 4:
						this.confirm_payment4();
						break;
					case 6:
						this.confirm_payment6();
						break;
					case 7:
						this.confirm_payment7();
						break;
				}

			},
			keyboardBackspace() {
				if (this.payment_password.length > 0) {
					this.payment_password.pop()
					this.$set(this.tips, this.payment_password.length, "__")
				}

				// console.log(this.payment_password, "刪除", this.tips)

			},
			cancel() {
				this.showKeyBoard = false
				this.tips = ["__", "__", "__", "__", "__", "__"]
				this.payment_password = []
			},
			keyboardChange(e) {
				if (this.payment_password.length < 6) {
					this.payment_password.push(e)
				}

				this.$set(this.tips, this.payment_password.length - 1, "*")

				// console.log(this.payment_password, "支付密碼", this.tips)
			},
			convertTime(num) {
				let time = new Date(num)
				let y = time.getFullYear()
				let m = this.montage(time.getMonth() + 1)
				let d = this.montage(time.getDate())
				return y + '/' + m + '/' + d
			},
			montage(num) {
				return num >= 10 ? num : '0' + num
			},
			selectCard(item) {
				if (this.rechargeCardInfo) {
					if (this.rechargeCardInfo.id == item.id) {
						this.rechargeCardInfo = null
					} else {
						this.rechargeCardInfo = item
					}
				} else {
					this.rechargeCardInfo = item
				}

				this.selectCardText = this.rechargeCardInfo ? this.rechargeCardInfo.title : '選擇儲值卡'

				this.showCardPopup = false
			},
			confirm_payment6() {
				if (Number(this.price) < Number(this.balance)) {
					ticketRollCardBuy({
						coupon_id: this.selectCouponId,
						store_id: this.storeDetails.id,
						card_id: this.details.id,
						type: 1, // 0--充值  1--購買電子票券  2--購買儲值卡
						pay_type: 6, // 1--信用卡付款  2--ATM付款  3--超商付款  4--line pay  5--儲值機  6--餘額
					}).then(res => {
						// console.log(res, "購買成功")
						if (res.code == 1) {
							uni.showToast({
								title: res.msg,
								icon: 'success',
								duration: 2000
							})
							this.showPayType = false

						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none',
								duration: 2000
							})
						}
					})
				} else {
					uni.showToast({
						title: '餘額不足',
						icon: 'none'
					})
				}
			},
			confirm_payment7() {

			},
			confirm_payment1() {
				ticketRollCardBuy({
					coupon_id: this.selectCouponId,
					store_id: this.storeDetails.id,
					card_id: this.details.id,
					type: 1, // 0--充值  1--購買電子票券  2--購買儲值卡
					pay_type: 1, // 1--信用卡付款  2--ATM付款  3--超商付款  4--line pay  5--儲值機  6--餘額
				}).then(res => {
					if (res.code == 1) {
						uni.navigateTo({
							url: `/pages/book_now/outward_payment/outward_payment?payData=${JSON.stringify(res.data)}&type=1`
						})
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				})
			},
			confirm_payment4() {
				ticketRollCardBuy({
					coupon_id: this.selectCouponId,
					store_id: this.storeDetails.id,
					card_id: this.details.id,
					type: 1, // 0--充值  1--購買電子票券  2--購買儲值卡
					pay_type: 4, // 1--信用卡付款  2--ATM付款  3--超商付款  4--line pay  5--儲值機  6--餘額
				}).then(res => {
					if (res.code == 1) {
						// uni.navigateTo({
						// 	url: `/pages/book_now/outward_payment/outward_payment?url=${res.data}`
						// })
						this.wakeUp(res.data.result)
						this.isLinePay = {
							flag: true,
							info: res.data.pay_log
						}
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				})
			},
			wakeUp(path) {
				const systemInfo = uni.getSystemInfoSync()
				// #ifdef APP-PLUS
				if (systemInfo.platform === 'Android') {
					const params = {
						pname: 'jp.naver.line.android',
						action: 'line://'
					}
					if (this.determine(params)) {
						// 已下載line pay
						plus.runtime.openURL(path, function() {
							// plus.nativeUI.alert('本機未安裝指定的應用')
						})
					} else {
						plus.runtime.openURL(`market://details?id=${params.pname}`, function() {
							// plus.nativeUI.alert('本機未安裝指定的應用')
						})
					}
				} else if (systemInfo.platform === 'ios') {
					const params = {
						appid: ''
					}
					plus.runtime.launchApplication({
						action: path
					}, function() {
						plus.nativeUI.actionSheet({
							title: '應用市場',
							cancel: '取消',
							buttons: [{
								title: '應用市場'
							}]
						}, function({
							index
						}) {
							switch (index) {
								case 1:
									plus.runtime.openURL(
										`itms-apps://itunes.apple.com`,
										function() {
											// plus.nativeUI.alert('本機未安裝指定的應用')
										})
							}
						})
					})
					// this.determine()
					plus.runtime.openURL(path, function() {
						// plus.nativeUI.alert('本機未安裝指定的應用')
					})
				}
				// #endif

				// #ifdef H5
				// uni.navigateTo({
				// 	url: `/pages/book_now/outward_payment/outward_payment?url=${path}&type=4`
				// })

				const userAgent = navigator.userAgent
				if (/(Android)/i.test(userAgent)) {
					// Android平台
					window.location.href = path
				} else if (/iPhone|iPad|iPod/i.test(userAgent)) {
					// ios平台
					window.location.href = path
				}

				// #endif

			},
			determine() {
				const install = plus.runtime.isApplicationExist()
				return install
			},
			linePayFn() {
				if (this.isLinePay.flag && this.isLinePay.info) {
					uni.showLoading({
						title: '加载中...'
					})
					setTimeout(() => {
						getLinePayInfo({
							...this.isLinePay.info
						}).then(res => {
							console.log(res)
							if (res.code == 1) {
								uni.showToast({
									title: res.msg,
									icon: 'success',
									duration: 6000
								})
								setTimeout(() => {
									uni.navigateBack()
								}, 1500)
							} else {
								uni.showToast({
									title: res.msg,
									icon: 'none',
									duration: 6000
								})
							}
						})
					}, 1000)
				}
			},

			confirm_payment2() {
				ticketRollCardBuy({
					coupon_id: this.selectCouponId,
					store_id: this.storeDetails.id,
					card_id: this.details.id,
					type: 1, // 0--充值  1--購買電子票券  2--購買儲值卡
					pay_type: 2, // 
				}).then(res => {
					if (res.code == 1) {
						uni.setStorageSync('MerchantTradeNo', res.data.MerchantTradeNo)

						uni.navigateTo({
							url: `/pages/book_now/outward_payment/outward_payment?form=${JSON.stringify(res.data)}&type=2`
						})
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				})
			},
			setPayment(arr) {
				if (this.first) return
				this.first = true
				arr.forEach(item => {
					console.log(item, '支付方式')
					switch (item) {
						case 1:
							this.paymentMethod.push({
								value: '信用卡/轉帳 藍新',
								checked: false
							})
							if (this.systemInfo.platform == 'ios' && this.storeDetails.id == 76) {
								this.paymentMethod.push({
									value: 'Apple pay',
									checked: false
								})
							}
							break;
						case 2:
							this.paymentMethod.push({
								value: '信用卡/轉帳 綠界',
								checked: false
							})
							break;
						case 4:
							if (this.storeDetails.id == 76) {
								this.paymentMethod.push({
									value: 'Line Pay',
									checked: false
								})
							}
							break;
						case 9:
							if (this.storeDetails.id == 76) {
								this.paymentMethod.push({
									value: 'Apple pay',
									checked: false
								})
							}

							break;
						case 10:
							if (this.systemInfo.platform == 'Android') {
								this.paymentMethod.push({
									value: 'Google pay',
									checked: false
								})
							}
							break;
					}
				})
			},
		},
		watch: {
			selectCouponId(n) {
				if (n !== "") {
					let discount = this.list.filter(item => item.id == n)[0]
					// console.log(discount,"111")
					this.price = this.details.money - discount.money
				} else {
					this.price = this.details.money
				}
			}
		}
	}
</script>

<style lang="less">
	.container {
		padding: 0 30rpx;
		box-sizing: border-box;

		.list {
			.list_item {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 30rpx 0rpx 25rpx;
				border-bottom: 1rpx solid #F2F2F2;
				font-size: 30rpx;

				.use_coupon {
					width: 251rpx;
					height: 68rpx;
					background: #39B19D;
					border-radius: 16rpx 16rpx 16rpx 16rpx;
					opacity: 1;
					color: #fff;
					text-align: center;
					line-height: 68rpx;
				}
			}
		}

		.service {
			font-size: 22rpx;
			color: #000;
			margin-top: 22rpx;
			display: flex;
			align-items: center;

			image {
				width: 32rpx;
				height: 29rpx;
				margin-right: 13rpx;
			}
		}

		.confirm_buy {
			font-size: 36rpx;
			font-weight: bold;
			color: #FA533D;
			display: flex;
			justify-content: space-between;
			align-items: center;
			position: fixed;
			left: 0%;
			bottom: 23rpx;
			padding: 30rpx;
			width: 100%;
			box-sizing: border-box;

			.confirm {
				width: 172rpx;
				height: 72rpx;
				background: #39B19D;
				border-radius: 16rpx 16rpx 16rpx 16rpx;
				opacity: 1;
				text-align: center;
				line-height: 72rpx;
				color: #fff;
			}
		}

		.popup {
			.popup_box {
				height: 60vh;
				background-color: #fff;
				padding: 30rpx;


				.popup_item {

					height: 154rpx;
					width: 100%;
					// background-color: #39B19D;
					background-color: #999;
					border-radius: 16rpx;
					border: 1rpx solid #F3F5F9;
					display: flex;
					margin-bottom: 30rpx;

					.list_left {
						width: 90%;
						height: 100%;
						background: #fff;
						border-radius: 16rpx;

						.top {
							height: 62rpx;
							border-bottom: 1rpx dashed #999;
							// padding-top: 15rpx;
							// box-sizing: border-box;
							display: flex;
							align-items: center;
							justify-content: space-between;
							position: relative;

							.coupon {
								font-size: 23rpx;
								font-weight: bold;
								margin-left: 44rpx;
								position: relative;

								&:before {
									content: '';
									display: block;
									width: 5rpx;
									height: 18rpx;
									background: linear-gradient(180deg, #00BC64 0%, #39B19D 100%);
									border-radius: 2rpx 2rpx 2rpx 2rpx;
									opacity: 1;
									position: absolute;
									left: -20rpx;
									top: 0;
									margin-top: 9rpx;
								}
							}

							.condition {
								font-size: 22rpx;
								color: #999;
								margin-right: 60rpx;
							}

							&:before {
								content: "";
								width: 20rpx;
								height: 20rpx;
								border-radius: 50%;
								background: #F3F5F9;
								display: block;
								position: absolute;
								left: 0%;
								bottom: 0%;
								margin-left: -10rpx;
								margin-bottom: -10rpx;
							}

							&::after {
								content: "";
								width: 20rpx;
								height: 20rpx;
								border-radius: 50%;
								// background: #39B19D;
								background: #999;
								display: block;
								position: absolute;
								right: 0%;
								bottom: 0%;
								margin-right: -10rpx;
								margin-bottom: -10rpx;
							}
						}

						.bottom {
							display: flex;
							align-items: flex-end;
							justify-content: space-between;

							.number {
								margin: 20rpx 0 0 34rpx;
								font-size: 38rpx;
								color: #FF6600;
								font-weight: bold;
							}

							.time {
								font-size: 22rpx;
								color: #999;
								margin-right: 50rpx;
							}
						}
					}

					.list_right {
						flex: 1;

						view {
							width: 100%;
							// 設置文本竪向排列
							writing-mode: vertical-lr;
							height: 154rpx;
							color: white;
							display: flex;
							align-items: center;
							justify-content: center;
							font-size: 23rpx;
							// 設置文字間隔
							letter-spacing: 13rpx;
						}
					}

				}

				.active {
					background-color: #39B19D;
					border: 1rpx solid #39B19D;

					.list_left {
						border-color: #39B19D;

						.top {
							border-color: #39B19D;

							&:before,
							&::after {
								background-color: #39B19D;
							}
						}
					}
				}
			}

			.popup_pay {

				padding-top: 145rpx;
				box-sizing: border-box;

				.radio_box {
					display: flex;
					flex-direction: column;
					padding: 0 67rpx 0 46rpx;
					box-sizing: border-box;

					label {
						display: flex;
						justify-content: space-between;
						align-items: center;
						margin-bottom: 33rpx;

						.active {
							color: #39B19D;
						}
					}
				}

				.confirm_payment {
					width: 476rpx;
					height: 110rpx;
					background: #39B19D;
					border-radius: 16rpx 16rpx 16rpx 16rpx;
					opacity: 1;
					font-size: 36rpx;
					line-height: 110rpx;
					text-align: center;
					color: white;
					margin: 97rpx auto;
				}

				.payment_method {
					position: relative;

					.balance {
						position: absolute;
						bottom: -10rpx;
						right: 67rpx;
						font-size: 24rpx;
					}

					.card_text {
						position: absolute;
						bottom: -60rpx;
						left: 46rpx;
						width: 100%;
						// padding: 0;
					}
				}
			}
		}

		/deep/ .u-fade-enter-active {
			z-index: 10076 !important;
		}

		/deep/ .u-slide-up-enter-active {
			z-index: 10076 !important;
		}

		.card_popup_box {
			width: 690rpx;
			max-height: 690rpx;
			border-radius: 16rpx;
			background-color: #fff;
			padding: 30rpx;
			box-sizing: border-box;

			.card_item {
				height: 150rpx;
				border-radius: 16rpx;
				border: 1rpx solid #F3F5F9;
				margin-bottom: 30rpx;
				background-color: #F3F5F9;
				padding: 20rpx;
				box-sizing: border-box;
				display: flex;
				flex-direction: column;
				justify-content: space-between;

				.title {
					display: flex;
					justify-content: space-between;
				}

				.card_balance {
					font-size: 30rpx;

					text {
						color: #FA533D;
						font-weight: bold;
						margin-left: 10rpx;
					}
				}
			}

			.active {
				background-color: #39B19D;
				color: #fff;
			}
		}

		/deep/ .u-transition {
			z-index: 10076 !important;
		}
	}
</style>